-
Notifications
You must be signed in to change notification settings - Fork 4
/
prog8.c
137 lines (115 loc) · 2.47 KB
/
prog8.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct node
{
char info;
struct node *left;
struct node *right;
};
typedef struct node *NODE;
struct stack
{
int top;
NODE data[10];
};
typedef struct stack STACK;
int preced(char item){
switch(item){
case '^': return 5;
case '*':
case '/': return 3;
case '+':
case '-': return 1;
}
}
void preorder(NODE root){
if(root != NULL){
printf("%c\t", root->info);
preorder(root->left);
preorder(root->right);
}
}
void inorder(NODE root){
if(root != NULL){
inorder(root->left);
printf("%c\t", root->info);
inorder(root->right);
}
}
void postorder(NODE root){
if(root != NULL){
postorder(root->left);
postorder(root->right);
printf("%c\t", root->info);
}
}
void push(STACK *s, NODE temp){
s->data[++(s->top)] = temp;
}
NODE pop(STACK *s){
return (s->data[(s->top)--]);
}
NODE createnode(char item){
NODE temp;
temp = (NODE)malloc(sizeof(struct node));
temp->info = item;
temp->left = NULL;
temp->right = NULL;
return temp;
}
NODE createExpTree(char expr[20]){
STACK tree, operator;
tree.top = -1;
operator.top = -1;
char symbol;
int i;
NODE temp, t, l, r;
for (i=0; expr[i] != '\0'; i++)
{
symbol = expr[i];
temp = createnode(symbol);
if(isalnum(symbol))
push(&tree, temp);
else{
if(operator.top == -1)
push(&operator, temp);
else{
while(operator.top != -1 && preced((operator.data[operator.top])->info) >= preced(symbol))
{
t = pop(&operator);
r = pop(&tree);
l = pop(&tree);
t->right = r;
t->left = l;
push(&tree, t);
}
push(&operator, temp);
}
}
}
while(operator.top != -1){
t = pop(&operator);
r = pop(&tree);
l = pop(&tree);
t->right = r;
t->left = l;
push(&tree, t);
}
return pop(&tree);
}
int main()
{
NODE root = NULL;
char expr[20];
printf("Read expression\n");
scanf("%s", &expr);
root = createExpTree(expr);
printf("\nInorder::");
inorder(root);
printf("\nPreorder:");
preorder(root);
printf("\nPostorder:");
postorder(root);
return 0;
}